﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using t_205_verk_hopur_12.Helpers;
using t_205_verk_hopur_12.Models;
using System.Web.Routing;

namespace t_205_verk_hopur_12.Authorize
{
    public class OwnerOrEmployeeAuthorize : AuthorizeAttribute
    {
        private Tool toolkit = new Tool();
        private ChannelRepository channelRepo = new ChannelRepository();

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return false;
            }

            return true;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            User currentUser = toolkit.GetCurrentUser();

            // We need a logged in user
            if (currentUser != null)
            {
                // Here we get the route data so we can get the channel id
                RouteValueDictionary routeValue = new RouteValueDictionary();
                int channelID = System.Convert.ToInt32(filterContext.Controller.ControllerContext.RouteData.Values["id"]);

                if (channelID == 0)
                {
                    channelID = System.Convert.ToInt32(filterContext.Controller.ControllerContext.RouteData.Values["channelID"]);
                }

                Channel channel = channelRepo.GetChannelByID(channelID);

                if (channel == null)
                {
                    // Unauthorized user
                    filterContext.Result = new HttpUnauthorizedResult();
                }

                if (channel != null)
                {
                    // If he is not the owner, then we check if he is an employee
                    if (channel.OwnerID != currentUser.ID)
                    {
                        // If you're not an employee, get out!
                        if (!channelRepo.IsEmployee(currentUser.ID, channel.ID))
                        {
                            // Unauthorized user
                            filterContext.Result = new HttpUnauthorizedResult();
                        }
                    }
                }
            }
            else
            {
                // Unauthorized user
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }
}